package com.bobo.web.provider.util.commutils;


import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class JsonResponseHandler implements ResponseHandler<String> {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
        int code = httpResponse.getStatusLine().getStatusCode();
        logger.info("code = {}", code);
        String json = null;
        HttpEntity httpEntity = httpResponse.getEntity();
        if (null != httpEntity) { //打印发挥的数据
            json = EntityUtils.toString(httpEntity);
            if (StringUtils.isNotBlank(json)) {
                if (json.length() > 1000) {
                    logger.info("response json = {}", json.substring(0, 1000));
                } else {
                    logger.info("response json = {}", json);
                }
            }
        }
        if (code == HttpStatus.SC_OK) {
            EntityUtils.consume(httpEntity);
            return json;
        } else {
            return null;
        }
    }
}
